package services;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Item;
import model.Photo;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import core.Lookup;
import core.ManagerLocal;

public class ItemPhotoUpload extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		
		
		FileItemFactory fileItemFactory = new DiskFileItemFactory();
		ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
		
		List fileItems;
		try {
			fileItems = servletFileUpload.parseRequest(req);
		
			Iterator iter = fileItems.iterator();
			
			Item item = null;
			FileItem fileUpload = null;
			
			while (iter.hasNext()) {
			    FileItem fileItem = (FileItem) iter.next();
	
			    if (fileItem.isFormField()) {
			    	Item itemResult = processFormField(fileItem);
			    	if(itemResult != null){
			    		item = itemResult;	
			    	}
			    } else {
			        fileUpload = fileItem;
			    }
			}	

			if(item == null){
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "item not found");
				return;
			}		

			if(fileUpload == null){
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "no upload");
				return;
			}		
			
			String relativePath = processUploadedFile(fileUpload, item);
			
			Photo photo = new Photo();
			photo.setItem(item);
			photo.setPath(relativePath);
			
			ManagerLocal manager = Lookup.lookupManager();
			
			manager.persist(photo);
			
			String outputString = "{success: true}";	
			
			PrintWriter writer = resp.getWriter();
			resp.setContentType("text/html;charset=UTF-8");
			writer.print(outputString);
			writer.close();
			
		} catch (Exception e) {
			throw new ServletException(e);
		}
			
	}

	private String processUploadedFile(FileItem fileItem, Item item) throws Exception {
//	    String fieldName = fileItem.getFieldName();
	    String fileName = fileItem.getName();
//	    String contentType = fileItem.getContentType();
//	    boolean isInMemory = fileItem.isInMemory();
//	    long sizeInBytes = fileItem.getSize();
	    
	    String realPath = System.getProperty("cattolica.photos.filepath");
	    String itemPath = realPath + "/" + item.getIdItem();
	    
		String relativePath = "/" + item.getIdItem() + "/" + fileName;
		String finalPath = realPath + relativePath;
		
		if(!new File(itemPath).exists()){
			new File(itemPath).mkdir();
		}
		
		File uploadedFile = new File(finalPath);
	    fileItem.write(uploadedFile);	    
    
		return relativePath;
	}

	private Item processFormField(FileItem fileItem) {
		Item item = null;
		String name = fileItem.getFieldName();
		if("idItem".equals(name)){
			ManagerLocal manager = Lookup.lookupManager();
		
			Integer idItem = new Integer(fileItem.getString());
			
			item = manager.get(Item.class, idItem);
		}
		return item;
	}

}
